const Util = require('./utils/util');
let qCloud = require('./index');
let sessionApp = require('./lib/session');

let session = sessionApp.get();
App({
    onShow: function () {
        // if (!session || !session.loginInfo && session.loginInfo.accessToken == "") {
        //   wx.reLaunch({
        //     url: '/pages/login/index',
        //   });
        //   return;
        // } else {
        //   wx.reLaunch({
        //     url: '/pages/index/index',
        //   });
        // }
    },

    onLaunch: function () {
        if (!session || !session.loginInfo && session.loginInfo.accessToken == "") {
            wx.reLaunch({
                url: '/pages/login/index',
            });
        } else {
            wx.reLaunch({
                url: '/pages/index/index',
            });
        }
    },

    fetchApis(pageSelf = '', url, params, method, success = (res) => {
    }, fail = (res) => {
    }, requireLogin = false) {
        let header = qCloud.buildSessionHeader();
        if (header.Authorization == "") {
            wx.reLaunch({
                url: '/pages/login/index',
            });
        }

        qCloud.request({
            login: requireLogin,
            url: `${url}`,
            method: method,
            header: header,
            data: params,
            success: function (res) {
                wx.hideNavigationBarLoading();
                wx.hideLoading();
                wx.stopPullDownRefresh();
                if (res.data.code === 2061 || res.data.code === 2041) {
                    sessionApp.clear();
                    wx.reLaunch({
                        url: '/pages/login/index',
                    });
                } else {
                    success(res);
                }
            },
            fail: function (err) {
                wx.hideNavigationBarLoading();
                wx.hideLoading();
                wx.stopPullDownRefresh();
                Util.showSelfModal(pageSelf, err.message);
                fail(err);
            }
        });
    },

    fetchNoTokenApis(pageSelf = '', url, params, method, success = (res) => {
    }, fail = (res) => {
    }, requireLogin = false) {
        qCloud.request({
            login: requireLogin,
            url: `${url}`,
            method: method,
            header: qCloud.buildSessionHeader(),
            data: params,
            success: function (res) {
                wx.hideNavigationBarLoading();
                wx.hideLoading();
                wx.stopPullDownRefresh();
                success(res);
            },
            fail: function (err) {
                wx.hideNavigationBarLoading();
                wx.hideLoading();
                wx.stopPullDownRefresh();
                Util.showSelfModal(pageSelf, err.message);
                fail(err);
            }
        });
    },

});
